package cn.springboot.erp.service.impl;

import cn.springboot.erp.commons.QueryParams;
import cn.springboot.erp.commons.ResponseResult;
import cn.springboot.erp.entity.User;
import cn.springboot.erp.mapper.UserMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.springboot.erp.entity.Dept;
import cn.springboot.erp.service.DeptService;
import cn.springboot.erp.mapper.DeptMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
* @author asus
* @description 针对表【dept】的数据库操作Service实现
* @createDate 2024-05-01 15:17:43
*/
@Service
public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept>
    implements DeptService{

    @Resource
    private UserMapper userMapper;
    @Override
    public ResponseResult listPage(QueryParams<Dept> queryParams) {
        // 获取分页参数
        Dept searchParams = queryParams.getSearchParams();
        Integer page = queryParams.getPage();
        Integer limit = queryParams.getLimit();
        // 执行分页操作
        Page<Dept> deptPage = new Page<>(page, limit);
        LambdaQueryWrapper<Dept> lambda = new QueryWrapper<Dept>().lambda();
        lambda.eq(StringUtils.isNotBlank(searchParams.getDeptName()),Dept::getDeptName,searchParams.getDeptName())
                .orderByDesc(Dept::getCreateTime);
        baseMapper.selectPage(deptPage,lambda);
        // 获取数据总条数
        long total = deptPage.getTotal();
        // 获取分页数据
        List<Dept> deptList = deptPage.getRecords();
        return ResponseResult.Success()
                .data("total",total)
                .data("deptList",deptList);
    }

    @Override
    public ResponseResult deleteById(Integer id) {
        // 根据部门id查询用户信息，查看部门中是否有员工
        LambdaQueryWrapper<User> lambda = new QueryWrapper<User>().lambda();
        lambda.eq(User::getDeptId,id);
        List<User> users = userMapper.selectList(lambda);
        // 如果"users"不为空，则表示部门有员工
        if (ObjectUtils.isNotNull(users)){
            return ResponseResult.Fail().msg("该部门有员工，暂时不可删除");
        }
        // 否则可以删除部门
        baseMapper.deleteById(id);
        return ResponseResult.Success().msg("删除成功");
    }
}




